/*
    Copyright (c);2019-2022;Wiscom System;

	All rights reserved.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the Wiscom System nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "los_hwi.h"
#include "los_task.h"
#include "los_api_bsp_can.h"
#include "los_inspect_entry.h"
#include "csg_sdk_hal.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cpluscplus */
#endif /* __cpluscplus */

static UINT32 g_uwTskCANID;
UINT8 g_CAN_flag=1;
#define TSK_PRIOR_HI 4
void CAN1_IRQHandler(void)
{
    CanReceiMsg receive_message;
    CanTransMsg transmit_message;
    /* initialize receive message */
    receive_message.rx_sfid = 0x00;
    receive_message.rx_efid = 0x00;
    receive_message.rx_ff = 0;
    receive_message.rx_dlen = 0;
    receive_message.rx_fi = 0;
    receive_message.rx_data[0] = 0x00;
    receive_message.rx_data[1] = 0x00;
    receive_message.rx_data[2] = 0x00;
    receive_message.rx_data[3] = 0x00;
    receive_message.rx_data[4] = 0x00;
    receive_message.rx_data[5] = 0x00;
    receive_message.rx_data[6] = 0x00;
    receive_message.rx_data[7] = 0x00;

    /* check the receive message */
    Can_Receive(CAN1, CAN_FIFO1, &receive_message);

    uint8_t transmit_mailbox = 0;

    /* initialize transmit message */
    transmit_message.tx_sfid = 0x22;
    transmit_message.tx_ft = CAN_FT_DATA;
    transmit_message.tx_ff = CAN_FF_STANDARD;
    transmit_message.tx_dlen = 8;
    transmit_message.tx_data[0] = receive_message.rx_data[0];
    transmit_message.tx_data[1] = receive_message.rx_data[1];
    transmit_message.tx_data[2] = receive_message.rx_data[2];
    transmit_message.tx_data[3] = receive_message.rx_data[3];
    transmit_message.tx_data[4] = receive_message.rx_data[4];
    transmit_message.tx_data[5] = receive_message.rx_data[5];
    transmit_message.tx_data[6] = receive_message.rx_data[6];
    transmit_message.tx_data[7] = receive_message.rx_data[7];

    /* transmit message */
    transmit_mailbox = Can_Transmit(CAN1, &transmit_message);
    // dprintf("\r\n4. CAN 0x22 IRQsend success!\r\n");

}
void can_config(uint8_t CanSpeed)
{
	/* Global interrupt enable*/
	__enable_irq();
	/*register interrupt CAN0_RX0_IRQn */
    LOS_HwiCreate(CAN1_IRQn, 1, ECLIC_NON_VECTOR_INTERRUPT, CAN1_IRQHandler, ECLIC_LEVEL_TRIGGER);

	// ECLIC_Register_IRQ(CAN1_IRQn, ECLIC_NON_VECTOR_INTERRUPT,
	//                                 ECLIC_LEVEL_TRIGGER, 1, 0,
	//                                 CAN1_IRQHandler);
	//CAN init
	Can_InitTypeDef can_parameter;
	Can_Filter_InitTypeDef can_filter;
	Can_StructInit(&can_parameter);
	
	/* initialize CAN */
	can_parameter.time_triggered = DISABLE;
	can_parameter.auto_bus_off_recovery = DISABLE;
	can_parameter.auto_wake_up = DISABLE;
	can_parameter.no_auto_retrans = DISABLE;
	can_parameter.rec_fifo_overwrite = DISABLE;
	can_parameter.trans_fifo_order = DISABLE;
	//can_parameter.working_mode = CAN_LOOPBACK_MODE;
	can_parameter.working_mode = CAN_NORMAL_MODE;
	/* configure baudrate to 20kbps:baudrate=sys_clk/prescaler/(SJW+BS1+BS) */
	can_parameter.resync_jump_width = CAN_BT_SJW_1TQ;
	can_parameter.time_segment_1 = CAN_BT_BS1_2TQ;
	can_parameter.time_segment_2 = CAN_BT_BS2_2TQ;
    if(CanSpeed==1)
    {
        can_parameter.prescaler = 80;							// 80分频250kHz频率
    }
	else
    {
        can_parameter.prescaler = 20;							// 20分频1MHz频率
    }
	Can_Init(CAN1, &can_parameter);							// CAN1初始化
	
	/* initialize filter */
	can_filter.filter_number = 0;
	
	/* initialize filter */
	can_filter.filter_mode = CAN_FILTERMODE_MASK;
	can_filter.filter_bits = CAN_FILTERBITS_32BIT;
	can_filter.filter_list_high = 0x0000;
	can_filter.filter_list_low = 0x0000;
	can_filter.filter_mask_high = 0x0000;
	can_filter.filter_mask_low = 0x0000;
	can_filter.filter_fifo_number = CAN_FIFO1;
	can_filter.filter_enable=ENABLE;
	Can_FilterInit(CAN1, &can_filter);
	
	/* enable CAN receive FIFO1 not empty interrupt  */
	Can_InterruptEnable(CAN1, CAN_INT_RFNE1);
}
void can_iomux_config(void)
{
	iomux_ls_iof_oval_cfg(IOMUX_BASE, CAN1_TX_IOF_OVAL, 70, CAN1_TX_HS_SEL, 0, 0);
	iomux_ls_iof_ival_cfg(IOMUX_BASE, CAN1_RX_IOF_IVAL, 72, CAN1_RX_HS_SEL, 0, 0);
}

static UINT32 Example_TaskHi(VOID)
{
    UINT32 uwRet = LOS_OK;
    UINT32 TempData = 0;
    uint8_t CanSpeed;
    uint8_t CanFinish;
    
    CanFinish=1;
    while(CanFinish==1)
    {
        dprintf("\r\n1. Send '0x01' to test 250kbps, Send '0x02' to test 1Mbps\r\n");
        CanSpeed=0;
        TempData=0;
        while(CanSpeed==0)
        {
            TempData=(USART0->RXDATA);
            if(TempData& USART_RXDATA_EMPTY)
            {
                TempData=0;
            }
            else
            {
                TempData=(TempData & 0xFF);
            }
            if(TempData==0x01)
            {
                CanSpeed=1;
            }
            else if(TempData==0x02)
            {
                CanSpeed=2;
            }
        }
        TempData=0;
        can1_clk_en(ENABLE);
        can1_set_rst(DISABLE);
        can1_set_rst(ENABLE);
        can_iomux_config();
        
        can_config(CanSpeed);
        dprintf("\r\n2. CAN init success!\r\n");
        g_CAN_flag=1;
        while (g_CAN_flag==1)
        {
            CanTransMsg transmit_message;

            uint8_t transmit_mailbox = 0;

            /* initialize transmit message */
            transmit_message.tx_sfid = 0x11;
            transmit_message.tx_ft = CAN_FT_DATA;
            transmit_message.tx_ff = CAN_FF_STANDARD;
            transmit_message.tx_dlen = 2;
            transmit_message.tx_data[0] = 0xAB;
            transmit_message.tx_data[1] = 0xCD;

            /* transmit message */
            transmit_mailbox = Can_Transmit(CAN1, &transmit_message);
            dprintf("\r\n3. CAN 0x11 send success!\r\n");
            dprintf("\r\n   send '0xA7' to continue test, send '0x57' to finish the test!\r\n");
            TempData=(USART0->RXDATA);
            if(TempData& USART_RXDATA_EMPTY)
            {
                TempData=0;
            }
            else
            {
                TempData=(TempData & 0xFF);
            }
            if(TempData==0xA7)
            {
                g_CAN_flag=0;
            }
            else if(TempData==0x57)
            {
                CanFinish=0;
                g_CAN_flag=0;
            }
            TempData=0;
            LOS_TaskDelay(3000);
        }
        
        g_CAN_flag=1;
        LOS_HwiDelete(CAN1_IRQn);
    }

    dprintf("\r\n5. BSP CAN test success!\r\n");
    LOS_InspectStatusSetByID(LOS_INSPECT_BSP_CAN,LOS_INSPECT_STU_SUCCESS);
    LOS_TaskDelete(g_uwTskCANID);
    return LOS_OK;
}

UINT32 Example_BSP_CAN(VOID)
{
    UINT32 uwRet;
    TSK_INIT_PARAM_S stInitParam;
    
    dprintf("\r\n--------4.27.7 BSP CAN test start!--------\r\n");
    /* lock task shcedue */
    LOS_TaskLock();

    stInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskHi;
    stInitParam.usTaskPrio = TSK_PRIOR_HI;
    stInitParam.pcName = "HIGH_NAME";
    stInitParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
    /* create high prio task */
    uwRet = LOS_TaskCreate(&g_uwTskCANID, &stInitParam);
    if (uwRet != LOS_OK)
    {
        LOS_TaskUnlock();

        dprintf("\r\nExample_TaskHi create Failed!\r\n");
        return LOS_NOK;
    }
    /* unlock task schedue */
    LOS_TaskUnlock();

    return uwRet;
}

#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cpluscplus */
#endif /* __cpluscplus */
